package cn.tworice.admin.web;

import cn.tworice.admin.service.LogService;
import cn.tworice.admin.service.LoginService;
import cn.tworice.admin.service.ResourcesService;
import cn.tworice.common.entity.Resources;
import cn.tworice.common.entity.dto.ResourcesDto;
import cn.tworice.common.vo.RequestResult;
import cn.tworice.common.vo.StatusCode;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("admin/system")
@Slf4j
@CrossOrigin
public class ResourcesController {

    @Autowired
    private ResourcesService service;

    @Autowired
    private LoginService loginService;

    @Autowired
    private LogService logService;

    @ApiOperation("编辑或添加资源")
    @PutMapping("resources/edit")
    @ApiImplicitParam(name = "id", value = "如修改，请添加ID", dataType = "int", dataTypeClass = Integer.class)
    public RequestResult editResources(Boolean router, Resources resources, HttpServletRequest request) {
        logService.addAdminLog(request.getHeader("adminID"), "添加/更新资源信息-" + resources.getName());

        RequestResult result = new RequestResult();
        int i = service.editResource(resources,router);
        if (i == 1) {
            result.setStatus(new StatusCode(200, "操作成功"));
        } else {
            result.setStatus(new StatusCode(500, "操作失败"));
        }
        return result;
    }

    @DeleteMapping("resources/del")
    @ApiOperation("删除资源")
    @ApiImplicitParam(name = "ids", value = "资源ID", required = true, dataType = "Array[Integer]", dataTypeClass = Integer[].class)
    public RequestResult delResources(Integer[] ids, HttpServletRequest request) {
        RequestResult result = new RequestResult();
        int i = service.delResources(ids);
        result.setStatus(new StatusCode(200, "删除" + i + "条"));
        logService.addAdminLog(request.getHeader("adminID"), "删除" + i + "条资源");
        return result;
    }

    @Deprecated
    @GetMapping("resources/conditionQuery")
    @ApiOperation("通过条件查询资源内容")
    public RequestResult conditionQueryResources(String name) {
        RequestResult result = new RequestResult();
        List<ResourcesDto> list = service.selectResources(name);
        result.setStatus(new StatusCode(200, "查询成功"));
        result.appendData("list", list);
        return result;
    }

    @GetMapping("resources/list")
    @ApiOperation("获取所有资源列表")
    public RequestResult resourcesList() {
        RequestResult result = new RequestResult();
        List<ResourcesDto> list = loginService.getResources("1");
        result.setStatus(new StatusCode(200, "查询成功"));
        result.appendData("resourceList", list);
        return result;
    }
}
